//
//  ZLTableviewExtension.swift
//  ZLExtension
//
//  Created by 科大 on 2025/1/8.
//

import UIKit

public extension UITableView {
    /// 滚动到底部
    func zl_scrollToBottom(delay: Double = 0, animated: Bool = true) {
        self.layoutIfNeeded()
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            // 确保表格数据加载完成后，滚动到底部
            let lastSection = self.numberOfSections - 1
            if lastSection >= 0 {
                let lastRow = self.numberOfRows(inSection: lastSection) - 1
                if lastRow >= 0 {
                    let indexPath = IndexPath(row: lastRow, section: lastSection)
                    self.scrollToRow(at: indexPath, at: .bottom, animated: animated)
                }
            }
        }
    }
    /// 滚动到底部
    func zl_scrollToLastSection(at: UITableView.ScrollPosition, delay: Double = 0, animated: Bool = true) {
        self.layoutIfNeeded()
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            let section = self.numberOfSections - 1
            if section < 0 {
                return
            }
            let sectionRow = self.numberOfRows(inSection: section)
            if sectionRow <= 0 {
                return
            }
            let indexPath = IndexPath(row: 0, section: section)
            self.scrollToRow(at: indexPath, at: at, animated: animated)
        }
    }
}
